//
//  FlutterOpenGlView.swift
//  flutter_test_opengl_plugin
//
//  Created by yuanxc on 2024/5/23.
//

import Foundation
import Flutter
import GLKit

class FlutterOpenGlView: NSObject, FlutterPlatformView {
    private var frame: CGRect
    private var viewId: Int64
    private var arguments: Any?
    private var message : FlutterBinaryMessenger
    
    private var channel: FlutterMethodChannel
    private var glViewController: GlViewController

    init(frame: CGRect, viewId: Int64, arguments: Any? = nil, message: FlutterBinaryMessenger) {
        self.frame = frame
        self.viewId = viewId
        self.arguments = arguments
        self.message = message

        // 绑定方法监听
        channel = FlutterMethodChannel(name: "flutter_opengl_view_\(viewId)", binaryMessenger: message)
        glViewController = GlViewController()
        super.init()

        channel.setMethodCallHandler { [weak self] in
            guard let `self` = self else { return }
            self.onMethodCall(call: $0, result: $1)
        }
    }

    func view() -> UIView {
        glViewController.getView ?? UIView()
    }
    

    func onMethodCall(call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "initGL":
            ready(call, result: result);
            break
        case "initGLNative":
            ready(call, result: result);
            break
        case "ready":
            ready(call, result: result);
            break
        case "stop":
            result(nil)
            break
        default:
            result(FlutterMethodNotImplemented);
        }
    }

    private func ready(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

    }
}
